package com.sunxd.zstudy.designPattern;

import com.google.common.collect.Lists;
import lombok.Data;

import java.util.List;

/**
 * 责任链
 *
 * @author: sun.xd
 * @date: 2021-10-14 14:26
 **/
public class M06_ChainOfResponsibility {


    public static void main(String[] args) {
//        String s = "大家好！我是lsp,<Script> 大家都是996";
//        s = s.replace("<", "[");
//        s = s.replace(">", "]");
//        s = s.replace("996", "995");
        // 1 list.add -> foreach 执行
//        ArrayList<MyFilter> myFilters = Lists.newArrayList();
//        myFilters.add(new HTMLFilter());
//        myFilters.add(new HTML2Filter());
//        myFilters.add(new SensitiveWordsFilter());
//        String finalS = s;
//        myFilters.forEach(x -> x.doMsg(finalS));
//        System.out.println(finalS);
        // 2 对1的优化
//        FilterChain filterChain = new FilterChain();
//        filterChain.add(new HTML1Filter()).add(new HTML2Filter()).add(new SensitiveWordsFilter());
//        filterChain.doFilter(s);
//        System.out.println(s);


    }

    interface MyFilter {
        String doMsg(String msg);
    }

    static class HTML1Filter implements MyFilter {
        @Override
        public String doMsg(String msg) {
            return msg.replace("<", "[");
        }
    }

    static class HTML2Filter implements MyFilter {
        @Override
        public String doMsg(String msg) {
            return msg.replace(">", "]");
        }
    }

    static class SensitiveWordsFilter implements MyFilter {
        @Override
        public String doMsg(String msg) {
            return msg.replace("996", "965");
        }
    }

    static class FilterChain {
        List<MyFilter> filters = Lists.newArrayList();

        public FilterChain add(MyFilter f) {
            filters.add(f);
            return this;
        }

        public void doFilter(String msg) {
            filters.forEach(x -> x.doMsg(msg));
        }
    }

    //------------------3--------------

    @Data
    abstract class HandlerChain{

        private HandlerChain handlerChain;

        public boolean handler(String s){
            if(canExecute(s)){
                execute(s);
            }else {
                handlerChain.execute(s);
            }
            return false;
        }
        public abstract boolean execute(String s);

        public abstract boolean canExecute(String s);
    }


}
